#!/usr/bin/python
# -*- coding: utf-8 -*-
# Created on 2017-02-16 下午3:26
# @auther: chenyongbing
# @file: forms.py

import os, logging

log = logging.getLogger(__name__)

from django import forms
from django.contrib import auth


class PasswordChangeForm(forms.Form):

    old_password = forms.CharField(label="旧密码",max_length=20,widget=forms.PasswordInput(attrs={'size': 20,"class":"form-control",}))
    new_password = forms.CharField(label="新密码",max_length=20,widget=forms.PasswordInput(attrs={'size': 20,"class":"form-control",}))
    repeat_password = forms.CharField(label="新密码确认",max_length=20,widget=forms.PasswordInput(attrs={'size': 20,"class":"form-control",}))

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(PasswordChangeForm, self).__init__(*args, **kwargs)
    def clean(self):
        try:
            old_passwd = self.cleaned_data['old_password']
        except:
            raise forms.ValidationError(u'旧密码错误')

        user = auth.authenticate(username=self.user, password=old_passwd)
        if user is None or not user.is_active:
            raise forms.ValidationError(u"旧密码错误")
        try:
            new_passwd = self.cleaned_data['new_password']
            repeat_passwd = self.cleaned_data['repeat_password']
        except:
            raise forms.ValidationError(u"请输入新密码")


        if new_passwd != repeat_passwd:
            raise forms.ValidationError(u"2次输入的新密码不一致")
        if old_passwd == new_passwd:
            raise forms.ValidationError(u"旧密码与新密码不能一致")

        try:
            user.set_password(new_passwd)
            user.save()
        except:
            raise forms.ValidationError(u"修改密码失败")

        return self.cleaned_data
